package com.huazai.service.impl;

import com.huazai.service.FileService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;

@Service
@Qualifier("FileServiceImpl")
public class FileServiceImpl implements FileService {

    /**
     * 注意：这个方法加上了锁（悲观锁），为了防止多线程的同时修改会引发命名不一致的问题。
     * 这个方法用于生成根据id生成的唯一资源标识路径
     *
     * @param preparedName     service层传入的ID值
     * @param originalFileName 将要上传的文件的全名
     * @return 返回的新的文件名
     */
    public synchronized String getNewName(String preparedName,
                                          String originalFileName) {
        String returnName = "";
        if (preparedName.endsWith("@qq.com")) {
            returnName += "用户";
            System.out.println(preparedName.substring(0, preparedName.indexOf("@qq.com")));
            returnName += preparedName.substring(0, preparedName.indexOf("@qq.com"));
        } else {
            returnName += "书封";
            returnName += preparedName;
        }
        return System.currentTimeMillis() + returnName + originalFileName.substring(originalFileName.lastIndexOf("."));
    }


    @Override
    public String uploadFileByPath(CommonsMultipartFile file,
                                   String uploadPath,
                                   String ID,
                                   String oldPath) {
        File filePath = new File(uploadPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        String originalName = file.getOriginalFilename();
        String newName = this.getNewName(ID, originalName);
        String temp = uploadPath.substring(0, uploadPath.indexOf("upload") - 1);

        File deleteFile = new File(temp, oldPath);

        if (deleteFile.exists() && ! deleteFile.toString().contains("无")) {
            deleteFile.delete();
        }

        File saveFile = new File(uploadPath, newName);

        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return newName;
    }
}
